package com.lzy.cloud.member.facade;

import com.alibaba.fastjson.JSON;
import com.lzy.cloud.member.constants.MemberConstants;
import com.lzy.cloud.member.dtos.MemberUserDto;
import com.lzy.cloud.member.remote.AccountWalletApi;
import com.lzy.cloud.member.remote.dtos.AccountWalletDto;
import com.lzy.cloud.member.remote.request.AccountWalletRequest;
import com.lzy.cloud.member.response.MemberToken;
import com.lzy.cloud.member.service.MemberUserService;
import com.lzy.framework.core.cache.cluster.RedisClusterService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.MD5Utils;
import com.lzy.framework.core.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by WIN7 on 2018/5/30.
 */
@Component
public class MemberUserFacade {

    @Autowired
    MemberUserService memberUserService;

    @Autowired
    private RedisClusterService redisClusterService;

    @Autowired
    private AccountWalletApi accountWalletApi;
    /**
     * 会员注册
     * @param dto
     * @return
     */
    public MemberUserDto registerMember(MemberUserDto dto){
        // 查询用户是否存在
        MemberUserDto memberUserDto = new MemberUserDto();
        memberUserDto.setPhone(dto.getPhone());
        List<MemberUserDto> list = memberUserService.selectList(memberUserDto);
        Ensure.that(list.size()).isGt(0,"00020001");

        String passMd5 =  MD5Utils.MD5(dto.getPassword()+MemberConstants.AFTERPASSWORD);
        dto.setPassword(passMd5);

        MemberUserDto resultDto = addMemberUser(dto);
        return resultDto;
    }

    /**
     * 登录验证(账号密码验证)
     * @param dto
     * @return
     */
    public MemberUserDto loginValidate(MemberUserDto dto) {
        // 查询用户在该平台下是否存在
        MemberUserDto memberUserDto = new MemberUserDto();
        memberUserDto.setPhone(dto.getPhone());
        memberUserDto.setPlatformId(dto.getPlatformId());
        List<MemberUserDto> list = memberUserService.selectList(memberUserDto);
        if (list.size() > 0) {
            // 该平台下用户存在，验证密码
            MemberUserDto dto2 = list.get(0);
            if(dto.getPassword() != null && dto2.getPassword() != null &&
                    MD5Utils.MD5(dto.getPassword()+MemberConstants.AFTERPASSWORD).equals(dto2.getPassword())) {
                    return dto2;
//                if (null != dto.getDeviceToken() && null != dto.getDeviceType()) {
//                    Boolean b = false;
//                    if (null == memberUserDto.getDeviceType() || !memberUserDto.getDeviceType().equals(dto.getDeviceType())) {
//                        memberUserDto.setDeviceType(dto.getDeviceType());
//                        b = true;
//                    }
//                    if (null == memberUserDto.getDeviceToken() || !memberUserDto.getDeviceToken().equals(dto.getDeviceToken())) {
//                        memberUserDto.setDeviceToken(dto.getDeviceToken());
//                        b = true;
//                    }
//                    if (b) {
//                        //先解除deviceToken占用，避免推送多次
//                        memberUserService.releaseTokenOccupancy(memberUserDto.getDeviceToken());
////                        memberUserService.updateMemberInfo(memberUserDto);
//                    }
//                }
            }
            return null;
        } else {
            memberUserDto.setPlatformId(null);
            list = memberUserService.selectList(memberUserDto);
            Ensure.that(list.size()).isGt(0, "00020007");
            MemberUserDto dto2 = list.get(0);
            if(dto.getPassword() != null && dto2.getPassword() != null &&
                    MD5Utils.MD5(dto.getPassword()+MemberConstants.AFTERPASSWORD).equals(dto2.getPassword())) {
                // 拷贝一个用户到该平台
                dto2.setPayPassword(null);
                dto2.setId(null);
                dto2.setPlatformId(dto.getPlatformId());
                MemberUserDto result = addMemberUser(dto2);
                return result;
            } else {
                return null;
            }
        }
    }

    public void updateMemberUser(MemberUserDto dto) {
        boolean isUpdatePayPassword = false;
        // 设置登录密码和支付密码
        if (dto.getPassword() != null) {
            String passMd5 = MD5Utils.MD5(dto.getPassword()+MemberConstants.AFTERPASSWORD);
            dto.setPassword(passMd5);
        }
        if (dto.getPayPassword() != null) {
            isUpdatePayPassword = true;
            String passMd5 =  MD5Utils.MD5(dto.getPayPassword()+MemberConstants.AFTERPASSWORD);
            dto.setPayPassword(passMd5);
        }
        Long platformId = dto.getPlatformId();
        String payPassword = dto.getPayPassword();

        // 查询所有平台下的用户
        MemberUserDto memberUserDto = new MemberUserDto();
        memberUserDto.setPhone(dto.getPhone());
        List<MemberUserDto> list = memberUserService.selectList(memberUserDto);

        // 修改用户
        for (int i = 0; i < list.size(); i++) {
            MemberUserDto dto2 = list.get(i);

            dto.setPayPassword(null);
            // 当前平台的用户 & 需要修改支付密码
            if (dto2.getPlatformId().equals(platformId) && isUpdatePayPassword) {
                dto.setPayPassword(payPassword);
            }
            dto.setId(dto2.getId());
            dto.setPlatformId(dto2.getPlatformId());
            Ensure.that(memberUserService.updateMemberUser(dto)).isTrue("00020006");
        }
    }

    /**
     * 移动端登录成功后：创建token信息
     *
     * @return
     */
    public String createAndSaveToken(MemberUserDto mDTO) {
        MemberToken token = new MemberToken();
        token.setToken(StringUtil.getUUID());
        token.setId(mDTO.getId());
        token.setPhone(mDTO.getPhone());
        token.setNickName(mDTO.getNickname());
        token.setIsClose(MemberConstants.TokenStatus.TOKEN_LOSE_NO);
        int minute = MemberConstants.TOKEN_TIME_MINUTE;
        redisClusterService.set(MemberConstants.TOKEN_KEY + token.getToken(),JSON.toJSONString(token),minute * 60);
        // 判断是否存在用户已经登录
//        MemberToken ut = kvClient.read(MemberConstants.TOKEN_KEY + mDTO.getId(), MemberToken.class);
        MemberToken ut = redisClusterService.get(MemberConstants.TOKEN_KEY + mDTO.getId(), MemberToken.class);
        if (null != ut) {// 发现已经有登录过，可能在另外一台手机登录
//            ut.setIsClose(CommonConstants.TokenStatus.TOKEN_T);// 设置被T标识
            List<String> tokens = new ArrayList<>();
            if (ut.getTokens() == null || ut.getTokens().size() == 0) {
                tokens.add(token.getToken());
                ut.setTokens(tokens);
            } else {
                ut.getTokens().add(token.getToken());
            }
//            kvClient.save(MemberConstants.TOKEN_KEY + mDTO.getId(), ut, minute * 60);
            redisClusterService.set(MemberConstants.TOKEN_KEY + mDTO.getId(), JSON.toJSONString(ut), minute * 60);
        } else {
            MemberToken userTokens = new MemberToken();
            List<String> tokens = new ArrayList<>();
            userTokens.setId(mDTO.getId());
            tokens.add(token.getToken());
            userTokens.setTokens(tokens);
            userTokens.setIsClose(MemberConstants.TokenStatus.TOKEN_LOSE_NO);
//            kvClient.save(MemberConstants.TOKEN_KEY + mDTO.getId(), userTokens, minute * 60);
            redisClusterService.set(MemberConstants.TOKEN_KEY + mDTO.getId(), JSON.toJSONString(userTokens), minute * 60);
        }
        return token.getToken();
    }

    /**
     * 处理编辑时的上级绑定时间
     *
     * @param memberUserDto
     */
    private void dealSuperTime(MemberUserDto memberUserDto) {
        //上级绑定时间的处理
        if (memberUserDto.getSuperId() != null && !"".equals(memberUserDto.getSuperId())) {
            MemberUserDto member = memberUserService.selectByMemberId(memberUserDto.getId());
            Ensure.that(member).isNotNull("00020007");
            //判断当上级重新绑定时，更新上级绑定时间
            if (member != null && member.getSuperId() != null && !"".equals(member.getSuperId()) && !member.getSuperId().equals(memberUserDto.getSuperId())) {
                memberUserDto.setSuperTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }
            //判断当之前没有上级的时候，添加上级绑定时间
            if (member != null && member.getSuperId() == null || "".equals(member.getSuperId())) {
                memberUserDto.setSuperTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }
        }
    }

    /**
     * 添加会员
     * @param dto
     * @return
     */
    private MemberUserDto addMemberUser(MemberUserDto dto) {
        Long id = memberUserService.addMemberUser(dto);
        Ensure.that(id).isGt(0,"00020002");

        AccountWalletDto accountWalletDto = new AccountWalletDto();
        accountWalletDto.setMemberId(id);
        accountWalletDto.setPlatformId(dto.getPlatformId());
        accountWalletApi.add(DozerUtils.map(accountWalletDto,AccountWalletRequest.class));

        dto.setId(id);
        return dto;
    }
}
